<template>
  <Dialog :appDialog="appDialog">
    <div class="depart_box">
      <div class="depart_l">
        <el-input v-model="searchName" class="search_name" placeholder="搜索成员、部门" :prefix-icon="Search" :filter-node-method="filterNode" />
        <el-scrollbar height="400px">
          <el-tree ref="treeRef" :data="depart" node-key="id" :props="defaultProps" default-expand-all :filter-node-method="filterNode">
            <template #default="{ node, data }">
              <!-- isMember -->
              <span class="custom-tree-node" v-if="true">
                <el-checkbox v-if="data.type == 'user'" v-model="data.check" class="depart_member" :disabled="data.disabled" @change="currentChange(data, node)">
                  <span>
                    <el-icon class="depart_member_icon">
                      <user-filled />
                    </el-icon>
                    <span>{{ node.label }}</span>
                  </span>
                </el-checkbox>
                <span v-else>
                  <img class="depart_icon" src="/static/depart.png" alt="" />
                  {{ node.label }}（{{ data.members || 0 }}）
                </span>
              </span>
              <span v-else class="custom-tree-node">
                <el-checkbox v-model="data.check" class="depart_member" @change="currentChange(data, node)">
                  <span>
                    <el-icon v-if="data.type == 'user'" class="depart_member_icon">
                      <user-filled />
                    </el-icon>
                    <img v-else class="depart_icon mr2" src="/static/depart.png" alt="" />
                    <span>{{ node.label }}</span>
                    <span>{{ data.type == 'user' ? '' : `（${data.members || 0}）` }}</span>
                  </span>
                </el-checkbox>
              </span>
            </template>
          </el-tree>
        </el-scrollbar>
      </div>
      <div class="depart_r">
        <div class="depart_select_title">已选择的员工</div>
        <el-scrollbar height="400px">
          <div class="seled_member" v-for="item in selectedMember" :key="item.id">
            <div class="item_member">
              <el-icon v-if="item.type == 'user'" class="seled_icon">
                <user-filled />
              </el-icon>
              <img v-else class="depart_icon" src="/static/depart.png" alt="" />
              <span class="member_name">{{ item.name }}</span>
            </div>
            <el-icon v-if="!item.disabled" @click="removeItem(item)" class="remove_icon">
              <close />
            </el-icon>
          </div>
        </el-scrollbar>
      </div>
    </div>
  </Dialog>
</template>
<script lang="ts" setup>
import { ref, reactive, watch, watchEffect, computed } from 'vue'
import Dialog from '@/components/Dialog.vue'
import { Search, UserFilled } from '@element-plus/icons-vue'
import type { ElTree } from 'element-plus'
import { getDepartUser } from '@/api/common'
import { IsNotEmpty } from '@/utils/utils'
import { useStore } from '@/store'
const emit = defineEmits(['submit'])
const store = useStore()
const treeRef = ref<InstanceType<typeof ElTree>>()

interface Tree {
  id: number
  label: string
  children?: Tree[]
}
interface Depart {
  title?: string
  creaters?: any[]
  isMember?: boolean
}
// 禁用成员
const disabledSelected = ref([])
// 选中人员新】
const selectedMember: any = ref([])

// 弹框
const departVisble = ref(false)
// 是否只支持人员信息
const isMember = ref([])
// 是否只支持人员信息
const title = ref('部门人员信息')
//确定
const submitHandel = () => {
  emit('submit', selectedMember)
  departVisble.value = false
}
//取消
const cancelHandel = () => {
  departVisble.value = false
}
const appDialog = reactive({
  visible: departVisble,
  title: title,
  width: '800px',
  cancel: cancelHandel,
  submit: submitHandel,
  cancelText: '取消',
  submitText: '保存',
  isInit: false, //是否重置
  isChooseDisabled: false, //重新打开传递进来的数据是否重置
  chooseArr: [], // 传递进来选中的数据 id
  multiple: true //是否是多选
})
const searchName = ref('')
const defaultProps = {
  children: 'children',
  label: 'name',
  disabled: 'disabled'
}
watch(searchName, (val) => {
  treeRef.value!.filter(val)
})
const filterNode = (value: string, data: Tree) => {
  if (!value) return true
  return data.name.indexOf(value) !== -1
}
const deteleObject = (obj: any) => {
  var uniques = []
  var stringify = {}
  for (var i = 0; i < obj.length; i++) {
    var keys = Object.keys(obj[i])
    keys.sort(function (a, b) {
      return Number(a) - Number(b)
    })
    var str = ''
    for (var j = 0; j < keys.length; j++) {
      str += JSON.stringify(keys[j])
      str += JSON.stringify(obj[i][keys[j]])
    }
    if (!stringify.hasOwnProperty(str)) {
      uniques.push(obj[i])
      stringify[str] = true
    }
  }
  uniques = uniques
  return uniques
}
// 过滤需要的人员信息
const filterMember = (data: any, isClearOther: boolean, disabledSelected: any[]) => {
  data = Array.isArray(data) ? data : [data]
  let arr: any[] = []
  data.forEach((item: any) => {
    item.disabled = false
    if (IsNotEmpty(disabledSelected) && disabledSelected.includes(item.id)) {
      item.disabled = true
    }
    if (IsNotEmpty(item.users)) {
      item.members = item.users.length
      if ((item.children && item.children.length == 0) || !item.children) {
        item.children = item.users
      } else {
        item.children = [...item.children, ...item.users]
      }
    }
    if (isClearOther) {
      let indx = selectedMember.value.findIndex((it: any) => it.id == item.id)
      item.check = indx > -1 ? true : false
    } else {
      if (appDialog.chooseArr.length > 0) {
        let indx = appDialog.chooseArr.findIndex((it: any) => it == item.id)
        item.check = indx > -1 ? true : false
        if (item.check && item.type !== "department") {
          item.disabled = appDialog.isChooseDisabled
          selectedMember.value.push(item)
          selectedMember.value = deteleObject(selectedMember.value)
        }
      } else {
        item.check = false
      }
    }
    if (IsNotEmpty(item.children)) {
      item.children = filterMember(item.children, isClearOther, disabledSelected)
    }
    arr.push(item)
  })
  return arr
}
const initDepart = async () => {
  const data = await getDepartUser()
  depart.value = filterMember(data, false, disabledSelected.value)
}
// 部门左侧树
const depart: any = ref([])
watch(
  () => appDialog.isInit,
  async (val) => {
    if (val) {
      selectedMember.value = []
      initDepart()
      appDialog.isInit = false
      console.log(depart.value, '===人源信息')
    }
  }
)
// 右侧选中
const currentChange = (item: Tree) => {
  // 如果是多选
  if (!appDialog.multiple) {
    selectedMember.value = item.check ? [item] : []
  } else {
    let indx = selectedMember.value.findIndex((it: any) => {
      return it.id == item.id
    })
    if (indx == -1) {
      selectedMember.value.push(item)
    } else {
      selectedMember.value.splice(indx, 1)
    }
  }
  filterMember(depart.value, true, disabledSelected.value)
}
// 删除选中成员信息
const removeItem = (data: any) => {
  let result = selectedMember.value.filter((item: any) => item.id != data.id)
  selectedMember.value = result
  depart.value = restoreDepart(data.id, depart.value)
}
// 删除右侧选中成员 恢复左边
const restoreDepart = (id: string, data: any) => {
  let arr: any[] = []
  data.forEach((item: any) => {
    if (item.id === id) {
      item.check = false
      if (item.type === 'department') {
        if (item.children && item.children.length > 0) {
          item.children = restore(item.children)
        }
      }
    } else {
      if (item.children && item.children.length > 0) {
        item.children = restoreDepart(id, item.children)
      }
    }
    arr.push(item)
  })
  return arr
}
// 查找部门的成员信息
const restore = (data: any) => {
  let arr: any[] = []
  data.map((item: any) => {
    item.check = false
    if (item.children && item.children.length > 0) {
      item.children = restore(item.children)
    }
    arr.push(item)
  })
  return arr
}

defineExpose({
  appDialog,
  departVisble,
  disabledSelected
})
</script>
<style lang="scss" scoped>
.depart_box {
  display: flex;
  .depart_member_icon {
    vertical-align: bottom;
    margin-right: 2px;
  }
  .depart_icon {
    width: 15px;
    vertical-align: middle;
  }
  .mr2 {
    margin-right: 2px;
  }
}
.depart_l {
  width: 350px;
  padding-right: 10px;
  border-right: 1px solid #eaeaea;
  .search_name {
    width: 259px;
    margin-bottom: 10px;
  }
  .custom-tree-node {
    display: flex;
    justify-content: center;
    align-items: center;
  }
  .is_member {
    // 不可全选样式
    :deep(.el-tree-node) {
      .is-leaf + .el-checkbox .el-checkbox__inner {
        display: inline-block;
      }
      .el-checkbox .el-checkbox__inner {
        display: none;
      }
    }
  }
}
.depart_r {
  padding: 10px 20px;
  flex: 1;
  .depart_select_title {
    margin-bottom: 20px;
  }
  .seled_member {
    line-height: 30px;
    display: flex;
    font-size: 14px;
    padding: 0 5px;
    align-items: center;
    justify-content: space-between;
    &:hover {
      background-color: rgba(255, 107, 0, 0.0901960784313725);
    }
    .item_member {
      display: flex;
      align-items: center;
      .seled_icon {
        color: #ff6b00;
      }
    }
    .member_name {
      margin-left: 2px;
    }
    .remove_icon {
      cursor: pointer;
      &:hover {
        transform: scale(1.23);
      }
    }
  }
}
</style>
